<template>
  <div class="chat-history">
    <!-- 侧边栏头部 -->
    <div class="sidebar-header">
      <div class="sidebar-title">
        <div class="chat-title" style="font-size: x-large;">Muti ai</div>
        <button class="collapse-btn" @click="toggleSidebar">
            <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="none" class="close-slide"><path d="M16.865 2.75H5.132a3.3 3.3 0 00-3.3 3.3v9.9a3.3 3.3 0 003.3 3.3h11.733a3.3 3.3 0 003.3-3.3v-9.9a3.3 3.3 0 00-3.3-3.3zM7.977 2.75v15.579" stroke="currentColor" stroke-width="1.54" stroke-linecap="round" stroke-linejoin="round"></path><path d="M15 8l-3 3 3 3" stroke="currentColor" stroke-width="1.54" stroke-linecap="round" stroke-linejoin="round"></path></svg>
        </button> 
      </div>
      <button class="new-chat-btn" @click="createNewChat">+ 新对话</button>
    </div>
    
    <!-- 历史对话列表 -->
    <div class="history-list">
      <div 
        v-for="(chat, index) in filteredChats" 
        :key="chat.id"
        :class="['history-item', { active: activeChatIndex === index }]"
        @click="selectChat(index)"
      >
        <div class="chat-info">
          <div class="chat-title">
            {{ chat.title || '新对话' }}
          </div>
          <div class="chat-preview">
            {{ chat.lastMessage || '开始对话...' }}
          </div>
        </div>
        <button 
          class="delete-btn"
          @click.stop="deleteChat(index)"
          title="删除对话"
        >
          🗑️
        </button>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredChats.length === 0" class="empty-state">
        <div class="empty-icon">📝</div>
        <p>暂无对话历史</p>
        <p class="empty-hint">开始新的对话吧！</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useSidebarStore } from '../stores/sidebar'

interface ChatHistory {
  id: string
  title: string
  lastMessage: string
  messageCount: number
}

// 使用Pinia store
const sidebarStore = useSidebarStore()

// 响应式数据
const searchQuery = ref('')
const activeChatIndex = ref(0)
const chatHistories = ref<ChatHistory[]>([])

/**
 * 切换侧边栏折叠/展开状态
 */
const toggleSidebar = () => {
  sidebarStore.toggle()
}

/**
 * 创建新对话
 * 保存当前对话到历史记录并清空当前对话
 */
const createNewChat = () => {
  // 获取当前对话内容
  const currentChat = localStorage.getItem('currentChat')
  
  if (currentChat) {
    try {
      const currentChatData = JSON.parse(currentChat)
      if (currentChatData.messages && currentChatData.messages.length > 0) {
        // 生成对话标题（使用第一条用户消息内容）
        const firstUserMessage = currentChatData.messages.find((msg: any) => msg.role === 'user')
        
        let title = '新对话'
          title = firstUserMessage.content.length > 20 
            ? firstUserMessage.content.substring(0, 20) + '...' 
            : firstUserMessage.content
      
        
        // 获取最后一条消息作为预览
        const lastMessage = currentChatData.messages[currentChatData.messages.length - 1]
        const lastMessageContent = lastMessage.content.length > 30
          ? lastMessage.content.substring(0, 30) + '...'
          : lastMessage.content
        
        // 保存完整的对话内容到本地存储
        const chatId = Date.now().toString()
        const chatData = {
          id: chatId,
          title: title,
          messages: [...currentChatData.messages], // 深拷贝消息数组
          timestamp: Date.now(),
          messageCount: currentChatData.messages.length
        }
        
        // 保存到本地存储
        const savedChats = JSON.parse(localStorage.getItem('savedChats') || '[]')
        savedChats.unshift(chatData)
        localStorage.setItem('savedChats', JSON.stringify(savedChats))
        
        // 保存到历史记录
        addNewChat(title, lastMessageContent)
      }
    } catch (error) {
      console.error('保存当前对话失败:', error)
    }
  }
  
  // 清空当前对话缓存
  localStorage.setItem('currentChat', JSON.stringify({ messages: [] }))
  
  // 触发自定义事件通知ChatWindow组件清空消息
  window.dispatchEvent(new CustomEvent('newChatCreated'))
}

// 过滤后的聊天历史
const filteredChats = computed(() => {
  if (!searchQuery.value) {
    return chatHistories.value
  }
  return chatHistories.value.filter(chat => 
    chat.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
    chat.lastMessage.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

/**
 * 生成消息数组的简单哈希
 * @param messages - 消息数组
 * @returns 哈希字符串
 */
const generateMessagesHash = (messages: any[]): string => {
  if (!messages || messages.length === 0) return 'empty';
  
  // 使用消息内容和角色的组合生成哈希
  return messages.map(msg => 
    `${msg.role}:${msg.content.substring(0, 50)}` // 只取前50个字符避免过长
  ).join('|');
}

/**
 * 选择聊天
 * @param index - 聊天在列表中的索引
 */
const selectChat = async (index: number) => {
  const selectedChat = filteredChats.value[index]
  
  // 保存当前对话到历史记录
  const currentChat = localStorage.getItem('currentChat')
  if (currentChat) {
    try {
      const currentChatData = JSON.parse(currentChat)
      if (currentChatData.messages && currentChatData.messages.length > 0) {
        // 检查当前对话是否已经有对应的历史记录
        const savedChats = JSON.parse(localStorage.getItem('savedChats') || '[]')
        const currentHash = generateMessagesHash(currentChatData.messages)
        const existingChat = savedChats.find((chat: any) => 
          generateMessagesHash(chat.messages) === currentHash
        )
        
        // 如果当前对话还没有保存到历史记录，则保存
        if (!existingChat) {
          // 生成对话标题
          const firstUserMessage = currentChatData.messages.find((msg: any) => msg.role === 'user')
          const firstAIMessage = currentChatData.messages.find((msg: any) => msg.role === 'ai')
          
          let title = '新对话'
          if (firstUserMessage && firstUserMessage.content) {
            title = firstUserMessage.content.length > 20 
              ? firstUserMessage.content.substring(0, 20) + '...' 
              : firstUserMessage.content
          } else if (firstAIMessage && firstAIMessage.content) {
            title = firstAIMessage.content.length > 20 
              ? firstAIMessage.content.substring(0, 20) + '...' 
              : firstAIMessage.content
          }
          
          // 获取最后一条消息作为预览
          const lastMessage = currentChatData.messages[currentChatData.messages.length - 1]
          const lastMessageContent = lastMessage.content.length > 30
            ? lastMessage.content.substring(0, 30) + '...'
            : lastMessage.content
          
          // 保存到历史记录
          addNewChat(title, lastMessageContent)
          
          // 保存到本地存储
          const chatId = Date.now().toString()
          const chatData = {
            id: chatId,
            title: title,
            messages: [...currentChatData.messages],
            timestamp: Date.now(),
            messageCount: currentChatData.messages.length
          }
          
          savedChats.unshift(chatData)
          localStorage.setItem('savedChats', JSON.stringify(savedChats))
        }
      }
    } catch (error) {
      console.error('保存当前对话失败:', error)
    }
  }
  
  // 加载选中的对话
  const savedChats = JSON.parse(localStorage.getItem('savedChats') || '[]')
  const chatToLoad = savedChats.find((chat: any) => chat.id === selectedChat.id)
  
  if (chatToLoad) {
    // 保存选中对话到currentChat
    localStorage.setItem('currentChat', JSON.stringify({
      messages: chatToLoad.messages,
      timestamp: Date.now()
    }))
    
    // 触发自定义事件通知ChatWindow组件加载消息
    window.dispatchEvent(new CustomEvent('chatSelected', { 
      detail: { messages: chatToLoad.messages } 
    }))
  }
  
  activeChatIndex.value = index
}

/**
 * 删除聊天
 * @param index - 聊天在列表中的索引
 */
const deleteChat = (index: number) => {
  const chatToDelete = filteredChats.value[index]
  
  // 添加滑动动画
  const chatItem = document.querySelectorAll('.history-item')[index]
  if (chatItem) {
    if (chatItem instanceof HTMLElement) {
      chatItem.style.transform = 'translateX(-100%)'
      chatItem.style.opacity = '0'
    }
    
    // 动画完成后删除
    setTimeout(() => {
      // 从本地存储中删除对话
      const savedChats = JSON.parse(localStorage.getItem('savedChats') || '[]')
      const updatedChats = savedChats.filter((chat: any) => chat.id !== chatToDelete.id)
      localStorage.setItem('savedChats', JSON.stringify(updatedChats))
      
      // 从历史记录中删除
      chatHistories.value.splice(index, 1)
      
      // 如果删除的是当前选中的对话，切换到第一个对话或清空
      if (activeChatIndex.value === index) {
        if (chatHistories.value.length > 0) {
          activeChatIndex.value = 0
          selectChat(0)
        } else {
          activeChatIndex.value = -1
          // 清空当前对话
          localStorage.setItem('currentChat', JSON.stringify({ messages: [] }))
          window.dispatchEvent(new CustomEvent('newChatCreated'))
        }
      } else if (activeChatIndex.value > index) {
        activeChatIndex.value = Math.max(0, activeChatIndex.value - 1)
      }
    }, 300)
  } else {
    // 如果没有找到元素，直接删除
    const savedChats = JSON.parse(localStorage.getItem('savedChats') || '[]')
    const updatedChats = savedChats.filter((chat: any) => chat.id !== chatToDelete.id)
    localStorage.setItem('savedChats', JSON.stringify(updatedChats))
    
    chatHistories.value.splice(index, 1)
    if (activeChatIndex.value >= index) {
      activeChatIndex.value = Math.max(0, activeChatIndex.value - 1)
    }
  }
}

/**
 * 添加新聊天（可以从外部调用）
 * @param title - 聊天标题
 * @param lastMessage - 最后一条消息内容
 */
const addNewChat = (title: string, lastMessage: string) => {
  const newChat: ChatHistory = {
    id: Date.now().toString(),
    title: title || '新对话',
    lastMessage,
    messageCount: 1
  }
  chatHistories.value.unshift(newChat)
  activeChatIndex.value = 0
  
  // 为新增的对话项添加滑入动画
  nextTick(() => {
    const newItem = document.querySelector('.history-item:first-child')
    if (newItem) {
      newItem.classList.add('slide-in')
      
      // 动画完成后移除动画类，避免重复动画
      setTimeout(() => {
        newItem.classList.remove('slide-in')
      }, 500)
    }
  })
}

// 暴露方法给父组件
defineExpose({
  addNewChat
})

// 初始化时从本地存储加载数据（如果有）
onMounted(() => {
  // 从chatHistories加载历史记录
  const savedHistories = localStorage.getItem('chatHistories')
  if (savedHistories) {
    try {
      chatHistories.value = JSON.parse(savedHistories)
    } catch (e) {
      console.error('加载聊天历史失败:', e)
    }
  }
  
  // 从savedChats加载对话数据
  const savedChats = JSON.parse(localStorage.getItem('savedChats') || '[]')
  if (savedChats.length > 0 && chatHistories.value.length === 0) {
    // 如果chatHistories为空但savedChats有数据，从savedChats同步数据
    chatHistories.value = savedChats.map((chat: any) => ({
      id: chat.id,
      title: chat.title,
      lastMessage: chat.messages[chat.messages.length - 1]?.content || '开始对话...',
      messageCount: chat.messageCount || chat.messages.length
    }))
  }
})

// 监听数据变化并保存到本地存储
watch(chatHistories, (newVal) => {
  localStorage.setItem('chatHistories', JSON.stringify(newVal))
}, { deep: true })
</script>

<style scoped src="@/styles/ChatHistory.css"></style>
